package com.study.ktandroid.coroutines_apply

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.study.ktandroid.databinding.ActivityCoroutineBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 传统回调 vs 协程
 */
class CoroutinesVSCallbackActivity01 : AppCompatActivity() {

    lateinit var binding: ActivityCoroutineBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCoroutineBinding.inflate(layoutInflater)
        setContentView(binding.root)
        userCallback()
        coroutineByCallAdapter()
        coroutineByCallSuspend()
    }

    // 传统callback,只能在回调中实现逻辑
    private fun userCallback() {
        gitHubApi.getUserCallBack("easyrose")
                .enqueue(object : Callback<User> {
                    override fun onResponse(call: Call<User>?, response: Response<User>?) {
                        response?.body()?.let { binding.callbackTv.text = it.toString() }
                    }

                    override fun onFailure(call: Call<User>?, t: Throwable?) {
                        print("error->${t?.message}")
                    }
                })
    }

    // 改造成协程的第一种方式CallAdapter/Deferred.await
    private fun coroutineByCallAdapter() {
        GlobalScope.launch(Dispatchers.Main) {
            val user: User = gitHubApi.getUserCallAdapterAsync("easyrose").await()
            binding.coroutineTv1.text = user.toString()
        }
    }

    // 使用Suspend函数
    private fun coroutineByCallSuspend() {
        GlobalScope.launch(Dispatchers.Main) {
            val user: User = gitHubApi.getUserSuspend("easyrose")
            binding.coroutineTv2.text = user.toString()
        }
    }
}